﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Input;
using jSLApp.Web.Workflow;
using jSLCore.Client.Presentation.BaseControl;
using jSLCore.Client.Presentation.BaseControl.DialogMessage;
using jSLCore.Client.Presentation.BaseControl.Selection;
using jSLCore.Utility.Extensions;
using Telerik.Windows.Controls;

namespace jSLApp.Client.Forms
{
    public partial class TagsDetail : DialogControl
    {
        private readonly string _tags;
        public TagsDetail(string tags):this()
        {
            _tags = tags;
        }

        public TagsDetail()
        {
            InitializeComponent();
        }

        public override void LoadInitialData()
        {
            var tags = _tags.Split(Constants.TagDelimiter);

            CurrentTags = CreatePack(tags).ToObservableCollection();

            LoadTagCloud();
        }

        private void LoadTagCloud()
        {
            DoWork("Загрузка облака тэгов",(sender, args) =>
                                               {
                                                   args.Result = Communication.Proxy.GetAllTags();
                                               },(o, eventArgs) =>
                                                     {
                                                         if(eventArgs.Error==null)
                                                         {
                                                             AllTags = (string[]) eventArgs.Result;
                                                         }
                                                     });
        }


        public ObservableCollection<StringPack> CurrentTags
        {
            get { return (ObservableCollection<StringPack>)currentGrid.ItemsSource; }
        set { currentGrid.ItemsSource = value; }}

        public string[] AllTags{get { return (string[]) allGrid.ItemsSource; }
        set { allGrid.ItemsSource = value; }}

        #region edit
        private void value_Validating(object sender, GridViewCellValidatingEventArgs e)
        {
            if (string.IsNullOrEmpty((string)e.NewValue))
            {
                e.IsValid = false;
                e.ErrorMessage = "Необходимо ввести значение";
                return;
            }

            e.IsValid = true;
        }

        private void edit_Ended(object sender, GridViewCellEditEndedEventArgs e)
        {
            DoWork(true, null, (o, args) =>
                                   {
                                       CheckDistinct();
                                   });
            
        }

        private void CheckDistinct()
        {
            again:
            {
            }

            var count = CurrentTags.Count;

            for (int i = 0; i < count; i++)
            {
                CurrentTags[i].Val = CurrentTags[i].Val.ToUpper();

                var currentTag = CurrentTags[i];

                for (int j = i + 1; j < count; j++)
                {
                    if (currentTag.Val.ToUpper() == CurrentTags[j].Val.ToUpper())
                    {
                        CurrentTags.RemoveAt(j);
                        goto again;
                    }
                }
            }
        }

        private void addtoCurrent_Clicked(object sender, RowSelectedEventArgs e)
        {
            var selString = (string)e.RowObject;

            AddToCurrent(selString);
        }

        private void AddToCurrent(string selString)
        {
            var strs = CurrentTags.Select(t => t.Val);
            if (strs.Contains(selString))
            {


                currentGrid.SelectedItem = CurrentTags.FirstOrDefault(c => c.Val.ToUpper() == selString.ToUpper());
            }
            else
            {
                CurrentTags.Insert(0, new StringPack { Val = selString });
            }
        }

        private void remove_Clicked(object sender, RowSelectedEventArgs e)
        {
            CurrentTags.Remove((StringPack) e.RowObject);
        } 
        #endregion

        private void text_Changed(object sender, TextChangedEventArgs e)
        {
            var searchText = txt.Text.ToUpper();

            var searched = AllTags.FirstOrDefault(t=>t.ToUpper().Contains(searchText));

            if(searched!=null)
            {
                allGrid.SelectedItem = searched;
                allGrid.ScrollIntoView(allGrid.SelectedItem);
            }
        }

        public override void OkClicked()
        {
            var result = string.Empty;

            foreach (var currentTag in CurrentTags)
            {
                result += currentTag.Val.ToUpper() + Constants.TagDelimiter;
            }

            result = result.TrimEnd(new[] {Constants.TagDelimiter});

            InvokeDataSelected(result);
        }


#region dialog

        public override bool IsOkVisible
        {
            get { return true; }
        }

        public override bool IsStandartOkCancelEnabled
        {
            get { return true; }
        }

        public override object OkContent
        {
            get { return "Сохранить"; }
        }

        public override Control GetControlForInitialFocus()
        {
            return txt;
        }

        protected override void AcceptButtonClicked()
        {
            
        }

        #endregion

        private static IEnumerable<StringPack> CreatePack(IEnumerable<string> vals)
        {
            return vals.Select(s=>new StringPack(){Val=s}).ToArray();
        }

        private void key_Down(object sender, KeyEventArgs e)
        {
            if(e.Key==Key.Enter)
            {
                if(allGrid.SelectedItem!=null)
                {
                    var str = (string)allGrid.SelectedItem;

                    AddToCurrent(str);
                }
            }
        }

        private void removeTag_Clicked(object sender, RowSelectedEventArgs e)
        {
            var dlg = new QuestionBox("Вы удаляете тэг из облака. Фильмы, отмеченные этим тэгом не исключат его. Продолжить?",QuestionBoxType.OkCancel);
            dlg.ShowDialog((o, data) => DoWork("Удаление тэга",(sender1, args) => Communication.Proxy.DeleteTag(args.String),(o1, eventArgs) =>
                                                                                          {
                                                                                              if(eventArgs.Error==null)
                                                                                              {
                                                                                                  LoadTagCloud();
                                                                                              }
                                                                                          }, e.RowObject));
        }
    }

    public class StringPack : INotifyPropertyChanged
    {
        public string Val { get; set; }
        public event PropertyChangedEventHandler PropertyChanged;

        public void InvokePropertyChanged()
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs("Val"));
        }
    }
}
